<template>
  <div class="app-container">
    <el-card>
      <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
      >
        <el-form-item label="站点名称">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入站点名称"
              clearable
              @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
              v-model="queryParams.status"
              clearable
              placeholder="请选择状态"
              style="width: 240px"
          >
            <el-option
                v-for="dict in contract_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="addDeviceTypes">新增</el-button>
        </el-col>

        <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="postList" stripe border max-height="500">
        <el-table-column label="站点名称" align="center" prop="name" />
        <el-table-column label="联系人" align="center" prop="contact" />
        <el-table-column label="联系电话" align="center" prop="phone" />
        <el-table-column label="站点地址" align="center" width="300">
          <template #default="scope">
            <span>{{scope.row.provinceName}}{{scope.row.cityName}}{{scope.row.countyName}}{{scope.row.address}} </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
<!--        <span>-->
<!--          {{contract_status.find(item=>item.value==scope.row.status)? contract_status.find(item=>item.value==scope.row.status).label:''}}-->

<!--        </span>-->
            <el-tag :type="scope.row.status === '1' ? '':'danger'">
              <span>   {{contract_status.find(item=>item.value==scope.row.status)? contract_status.find(item=>item.value==scope.row.status).label:''}}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="notes" show-overflow-tooltip width="400" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary"  @click="edit(scope.row)">修改</el-button>
            <el-button link type="primary"  @click="goPeople(scope.row)">站点人员</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.page"
          v-model:limit="queryParams.limit"
          @pagination="getList"
      />
    </el-card>
    <el-dialog
        v-model="open"
        :title="title"
        append-to-body
        width="800px"
        v-if="open"
        @close="cancel"
        :close-on-click-modal="false"
    >
      <el-form
          ref="communitySiteRef"
          :model="form"
          :rules="rules"
          label-width="110px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="站点名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入站点名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="站点地址" prop="provinceId" style="font-weight: 700">
              <el-select v-model="form.provinceId"  placeholder="选择省" style="width: 200px"  @change="changeProvince">
                <el-option
                    v-for="dict in regionList "
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                ></el-option>
              </el-select>
              <el-select v-model="form.cityId"  placeholder="选择市" style="width: 200px;margin-left: 10px" @change="changeCity" >
                <el-option
                    v-for="dict in CityList "
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                ></el-option>
              </el-select>
              <el-select v-model="form.countyId"  placeholder="选择区/县" style="width: 200px;margin-left: 10px" @change="changeCounty" >
                <el-option
                    v-for="dict in countyList "
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" >
              <el-radio-group v-model="form.status">
                  <el-radio
                      v-for="(item, index) in contract_status"
                      :key="index"
                      :label="item.value"
                  >{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                  v-model="form.notes"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 8 }"
                  placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改岗位对话框 -->
  </div>
</template>

<script setup name="communitySite">
  const { proxy } = getCurrentInstance();
  const router = useRouter();
  const { sys_normal_disable, sys_user_sex, device_category,contract_status } = proxy.useDict(
      "sys_normal_disable",
      "sys_user_sex",
      "device_category",
      "contract_status"
  );
  import {
    communitySite, communitySiteDel, communitySiteSave, communitySiteUpdata
  } from "@/api/homeBed/index";

  import { debounce } from "@/utils/debounce.js";
  import  {region} from '@/api/record/api'
  const showSearch = ref(true);
  const loading = ref(true);
  const postList = ref([]);
  const open = ref(false);
  const title = ref("新增社区站点");
  const regionList=ref([]);
  const CityList=ref([]);
  const countyList=ref([])

  const total = ref(0);

  const data = reactive({
    form: {
      status:'1'
    },
    queryParams: {
      page: 1,
      limit: 10,
      name: undefined,
      status:undefined

    },
    rules: {
      name: [
        { required: true, message: "请输入站点名称", trigger: "blur" },
      ],
      contact: [
        { required: true, message: "请输入联系人", trigger: "blur" },
      ],
      phone:[{ required: true, message: "请输入正确手机号", trigger: "blur"},{pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}],
      provinceId:[{ required: true, message: "请选择站点地址", trigger: "change" }],
      address:[  { required: true, message: "请输入详细地址", trigger: "blur" },]
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  /**
   * 提交按钮
   */
  const submitFormDebounceHandler = debounce(submitForm, 500);

  function submitForm() {
    proxy.$refs["communitySiteRef"].validate((valid) => {
      if (valid) {
        if (form.value.id != undefined) {
          communitySiteUpdata(form.value).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            reset();
            getList();
          });
        } else {
          communitySiteSave(form.value).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            reset();
            getList();
          });
        }
      }
    });
  }

  function cancel() {
    open.value = false;
    reset();
  }

  function goPeople(data){
    router.push({
      path:`/communityManagement/communityPeople/org/${data.id}`
    })
  }

  async function edit(data) {
    form.value = data;
    const data1 = await region(data.provinceId)
    const data2 = await region(data.cityId)
    CityList.value = data1.data
    countyList.value = data2.data
    title.value = "编辑社区站点";
    open.value = true;
  }

  function reset() {
    form.value = {
      id: null,
      name: undefined,
      contact: undefined,
      phone: undefined,
      provinceId:null,
      cityId:null,
      countyId:null,
      provinceName:null,
      cityName:null,
      countyName:null,
      address:null,
      status:'1',
      notes:null

    };
    proxy.resetForm("communitySiteRef");
    CityList.value = []
    countyList.value = []
  }

  /** 查询岗位列表 */
  function getList() {
    loading.value = true;
    communitySite(queryParams.value).then((response) => {
      postList.value = response.page.list;
      total.value = response.page.totalCount;
      loading.value = false;
    });
  }

  function handleQuery() {
    getList();
  }

  function resetQuery() {
    queryParams.value = {
      page: 1,
      limit: 10,
      name: undefined,
      status:undefined
    };
    getList();
  }

  function handleDelete(row) {
    proxy.$modal
        .confirm("是否确认删除该数据项？")
        .then(function () {
          return communitySiteDel([row.id]);
        })
        .then(() => {
          getList();
          proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
  }

  function addDeviceTypes() {
    title.value = "新增社区站点";
    open.value = true;
  }

  function getregion(){
    region(0).then(res=>{
      console.log(res)
      regionList.value=res.data
    })
  }

  function changeProvince(val){
    form.value.provinceName = regionList.value.find(item =>item.areaCode==val)?.name
    CityList.value = []
    form.value.cityId = ''
    form.value.countyId = ''
    countyList.value = []
    region(val).then(res=>{
      CityList.value = res.data
    })
  }

  function changeCity(val){
    form.value.cityName = CityList.value.find(item=>item.areaCode==val)?.name
    form.value.countyId = ''
    countyList.value = []
    region(val).then(res=>{
      countyList.value=res.data
    })
  }

  function changeCounty(val){
    form.value.countyName=countyList.value.find(item=>item.areaCode==val)?.name
  }

  getList();
  getregion()
</script>
